
package botlab.gui.actionlistener;

import botlab.gui.GUI;
import botlab.gui.filefilter.CustomFileFilter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;

/**
 *
 * @author Quentin
 */
public class SaveActionListener implements ActionListener
{
    private GUI gui;
    private final JFileChooser fc;
    
    public SaveActionListener(GUI gui)
    {
        this.gui=gui;
        fc=new JFileChooser();
        fc.setAcceptAllFileFilterUsed(false);
        fc.addChoosableFileFilter(new CustomFileFilter("botlab","Botlab's file type (.botlab)"));
    }
    
    public void actionPerformed(ActionEvent e)
    {
        int returnVal = fc.showSaveDialog(gui.getFrame());

        if (returnVal == JFileChooser.APPROVE_OPTION) 
        {
            File file = fc.getSelectedFile();
            CustomFileFilter filter =(CustomFileFilter) fc.getFileFilter();
            
            // we add the extension if not set
            String ext = filter.getFileExtension(file);
            if(ext == null || !ext.equals("botlab"))
                file = new File(file.getAbsolutePath()+"."+filter.getExtension());
            
            String textToSave = gui.getEditorPane().getText();
            
            BufferedWriter writer = null;
            try
            {
                writer = new BufferedWriter(new OutputStreamWriter(
                        new FileOutputStream(file), "UTF-8"));
                writer.write(textToSave);
                writer.flush();
                writer.close();
            }
            catch (IOException ex)            
            {
                Logger.getLogger(SaveActionListener.class.getName()).log(Level.SEVERE,
                        null, ex);
            }            
        }
    }
    
}
